/* 
    工具类
*/

//格式化时间
export function formatDate(val,type){
    let date = val === null ? new Date() : new Date(val);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let h = date.getHours();
    let m = date.getMinutes();
    let s = date.getSeconds();
    if(type === 0){
        return year + "-" + addZero(month) + "-" + addZero(day) + " " + addZero(h) + ":" + addZero(m) + ":" + addZero(s);
    } else if (type === 1){
        return year + "-" + addZero(month) + "-" + addZero(day);
    } else if (type === 2){
        return addZero(h) + ":" + addZero(m) + ":" + addZero(s);
    } else if (type === 3){
        return year + "-" + addZero(month) + "-" + addZero(day) + " 00:00:00";
    }
}

function addZero(val){
    return val > 9 ? val : "0" + val;
}

export async function sleep(seconds = 0){
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve('end');
        }, seconds);
    })
}


/**
 * 通过精致token获取登录用户信息
 * @param token 
 * @returns 用户信息 | 错误提示
 */
export const getUserInfoByToken = (token = null) => {
    const isDevelopment = process.env.NODE_ENV === 'development';
    if(token === null) {
        if(isDevelopment){
            token = process.env.VUE_APP_APPLICATION_TOKEN;
        } else {
            token = localStorage.getItem("Token");
        }
    }
    const strings = token.split('.') //通过split()方法将token转为字符串数组
    //取strings[1]数组中的第二个字符进行解析
    const userinfo = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, '+').replace(/_/g, '/')))));
    console.log("通过token解析出来的用户信息==>",userinfo);
    return userinfo;
}